package org.as.sdg.beans;

import java.io.Serializable;
import java.util.Collection;
import java.util.Enumeration;

import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.as.sdg.builder.ApplicationBuilder;
import org.as.sdg.objs.Node;
import org.as.sdg.util.FacesUtils;

import com.icesoft.faces.component.paneltabset.TabChangeEvent;

@SuppressWarnings("serial")
public class ApplicationController implements Serializable {
	private static final Log logger = LogFactory
			.getLog(ApplicationController.class);

	public void processTabChange(TabChangeEvent tabChangeEvent)
			throws AbortProcessingException {

	}

	public void navigationEvent(ActionEvent event) {
		// get id of node that was clicked on.
		String nodeId = FacesUtils.getRequestParameter("nodeId");

		// get a reference to the application scoped application builder.
		ApplicationBuilder applicationBuilder = (ApplicationBuilder) FacesUtils
				.getManagedBean("applicationBuilder");

		// do a bean lookup by node Id
		Node node = applicationBuilder.getNode(nodeId);

		// not all notes are marked as links and some nodes may be null
		// if the meta data was not correctly validated.
		if (node != null && node.isLink()) {

		} else if (node != null && !node.isLink()) {
			toggleTreeNodeExpandedState(node.getId());
		}
	}

	/**
	 * Utility method to toggle the selected state of the specified node.
	 * 
	 * @param nodeId
	 *            nodeId of the the node to toggle the expanded state of.
	 */
	private void toggleTreeNodeExpandedState(String nodeId) {
		DefaultMutableTreeNode defaultNode = findTreeNode(nodeId);
		if (defaultNode != null) {
			NavigationTreeNode node = (NavigationTreeNode) defaultNode
					.getUserObject();
			node.setExpanded(!node.isExpanded());
		}
	}

	private DefaultMutableTreeNode findTreeNode(String nodeId) {
		ApplicationSessionModel applicationModel = (ApplicationSessionModel) FacesUtils
				.getManagedBean("applicationSessionModel");
		Collection<DefaultTreeModel> trees = applicationModel
				.getNavigationTrees().values();

		DefaultMutableTreeNode node;
		DefaultMutableTreeNode rootNode;
		// search all trees defined by meta data using a depthFirst search.
		for (DefaultTreeModel treeModel : trees) {
			rootNode = (DefaultMutableTreeNode) treeModel.getRoot();
			Enumeration nodes = rootNode.depthFirstEnumeration();
			while (nodes.hasMoreElements()) {
				node = (DefaultMutableTreeNode) nodes.nextElement();
				NavigationTreeNode tmp = (NavigationTreeNode) node
						.getUserObject();
				if (tmp.getNodeId() != null && tmp.getNodeId().equals(nodeId)) {
					return node;
				}
			}
		}
		return null;
	}
}
